package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.vo.TimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 预约信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-15
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 小程序端新增预约信息
     *
     * @param reservationDto
     */
    @Override
    public void addReservation(ReservationDto reservationDto) {

        //判断改手机号是否已经预约过当前时间
        LambdaQueryWrapper<Reservation> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getMobile,reservationDto.getMobile())
                .eq(Reservation::getTime,reservationDto.getTime());
        if(count(queryWrapper)>0){
            throw new BaseException("该手机号已预约当前时间");
        }
        Reservation reservation = new Reservation();
        BeanUtil.copyProperties(reservationDto,reservation);

        //从线程局部变量中获取当前登陆用户的id
        Long userId = UserThreadLocal.get();
        reservation.setUserId(userId);


        //设置探访人 根据预约类型判断如果为参观预约则返回参观预约 如果为探访预约则返回老人姓名
        reservation.setVisitor(reservationDto.getType()==0?reservationDto.getVisitor(): null);
        //根据当前时间获取预约状态(定时更新)
        reservation.setStatus(0);
        reservation.setTime(LocalDateTime.now());

        save(reservation);
    }

    /**
     * 小程序查询预约信息列表
     *
     * @param status
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public List<Reservation> selectMemberReservationList(Integer status, Integer pageSize, Integer pageNum) {
        Page<Reservation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Reservation> queryWrapper=new LambdaQueryWrapper<>();
       //如果status为null则查询所有状态的预约信息
        if(status==null){
            queryWrapper.isNotNull(Reservation::getStatus);
        }else {
            queryWrapper.eq(Reservation::getStatus,status);
        }

        page = page(page, queryWrapper);
        return page.getRecords();
    }

    /**
     * 定时更新预约状态
     */
    @Override
    public void updateReservationStatus() {
        //查询所有状态为0,的预约信息
        List<Reservation> reservationList = list(Wrappers.<Reservation>lambdaQuery().ne(Reservation::getStatus,2).ne(Reservation::getStatus, 1));

        reservationList.forEach(reservation -> {
            if(reservation.getTime().isBefore(LocalDateTime.now())){
                //修改状态为1
                reservation.setStatus(3);
            }
        });
              System.out.println(reservationList);
             updateBatchById(reservationList);
    }

    /**
     * 取消预约
     * 根据id 更新预约状态
     *
     * @param id
     */
    @Override
    public void UpdateReservationById(Long id) {

        Reservation reservation = selectReservationById(id);
        reservation.setStatus(2);
        //修改状态为2

        updateById(reservation);
    }

    /**
     * 根据用户id查询当天取消的次数
     *
     * @param userId
     * @return
     */
    @Override
    public int getCancelledReservationCount(Long userId) {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        LambdaQueryWrapper<Reservation> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getUserId,userId)
                .between(Reservation::getCreateTime,startTime,endTime)
                .eq(Reservation::getStatus,2);

       //根据用户id和当天时间查询状态为2的预约信息数量
      //  return reservationMapper.selectCount(Wrappers.<Reservation>lambdaQuery().eq(Reservation::getUserId, userId.intValue()).between(Reservation::getCreateTime,startTime,endTime).eq(Reservation::getStatus,2)).intValue();
        long count = count(queryWrapper);

        return (int) count;
    }

    /**
     * 查询剩余预约数量
     *
     * @param time
     * @return
     */
    @Override
    public List<TimeVo> selectRemainCount(Long time) {
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime start = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = start.plusDays(1);
        List<TimeVo> timeVos = reservationMapper.selectRemainCount(start, endTime);
        return timeVos;
    }
}
